package com.example.admin.goodnews.fragment.ShengHuoChangYong;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TextInputLayout;
import android.support.v4.app.Fragment;
import android.support.v4.util.ArrayMap;
import android.support.v7.widget.AppCompatSpinner;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;

import com.example.admin.goodnews.R;
import com.example.admin.goodnews.adapter.KuaiDiAdapter;
import com.example.admin.goodnews.entity.KuaiDiGongSiDataEntity;
import com.example.admin.goodnews.entity.KuaiDiJieGuoDataEntity;
import com.example.admin.goodnews.utils.GetCurrentTimeUtil;
import com.example.admin.goodnews.utils.HttpUtils;
import com.example.admin.goodnews.utils.NetWorkDataUrl;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 快递查询页面
 * Created by admin on 2016/10/24.
 */

public class KuaiDiChaXunFragment extends Fragment {
    private AppCompatSpinner appcompatspinner_kuaidi;// 下拉框
    private RelativeLayout relativeLayout_kuaidi;
    private TextView tv_error;// 错误信息
    private TextInputLayout til_kuaidi;// 输入框
    private EditText et_kuaidi;
    private RecyclerView recyclerview_kuaidi;
    private Button btn_find_kuaidi;// 点击查询按钮
    private Button btn_reset_kuaidi;// 点击重置按钮
    private LinearLayoutManager linearLayoutManager;// 布局管理器
    private KuaiDiGongSiDataEntity kuaiDiGongSiDataEntity;// 快递公司实体类
    private KuaiDiJieGuoDataEntity kuaiDiJieGuoDataEntity;// 快递查询结果实体类
    private KuaiDiAdapter kuaiDiAdapter;// 快递结果适配器
    private String time = GetCurrentTimeUtil.getCurrentTime();// 获取系统当前时间
    private Map<String, String> company;
    private List<String> namelists;
    private String simpleName;// 存放快递公司的拼音
    private String number;// 保存快递单号


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_kuaidichaxun, null);
        appcompatspinner_kuaidi = (AppCompatSpinner) view.findViewById(R.id.appcompatspinner_kuaidi);
        tv_error = (TextView) view.findViewById(R.id.tv_error);
        relativeLayout_kuaidi = (RelativeLayout) view.findViewById(R.id.relativeLayout_kuaidi);
        til_kuaidi = (TextInputLayout) view.findViewById(R.id.til_kuaidi);
        recyclerview_kuaidi = (RecyclerView) view.findViewById(R.id.recyclerview_kuaidi);
        btn_find_kuaidi = (Button) view.findViewById(R.id.btn_find_kuaidi);
        btn_reset_kuaidi = (Button) view.findViewById(R.id.btn_reset_kuaidi);

        linearLayoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
        recyclerview_kuaidi.setLayoutManager(linearLayoutManager);// 设置布局管理器

        getCompany();// 获取快递公司数据

        et_kuaidi = til_kuaidi.getEditText();
        et_kuaidi.setHint("请输入快递单号");
        TextChange textChange = new TextChange();
        et_kuaidi.addTextChangedListener(textChange);

        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        // 点击查询
        btn_find_kuaidi.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getData();
            }
        });
        // 点击重置
        btn_reset_kuaidi.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                et_kuaidi.setText("");
            }
        });
    }

    // 获取快递公司数据
    private void getCompany() {
        String url = "https://route.showapi.com/64-20";
        String param = "expName=&maxSize=&page=&showapi_appid=25336&showapi_timestamp=20161024173431&showapi_sign=41d40a32749d9875ba2df794d9529081";
        try {
            HttpUtils.doPostAsyn(url, param, new HttpUtils.CallBack() {
                @Override
                public void onRequestComplete(String result) {
                    Gson gson = new Gson();
                    kuaiDiGongSiDataEntity = gson.fromJson(result, KuaiDiGongSiDataEntity.class);
                    if (kuaiDiGongSiDataEntity.getShowapi_res_body().getExpressList().size() > 0) {
                        handler.sendEmptyMessage(1);
                    } else {
                        handler.sendEmptyMessage(0);
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 通过快递公司名称的拼音和快递单号获取数据
    private void getData() {
        String param = NetWorkDataUrl.KUAIDICHAXUN_PARAM1 + simpleName + NetWorkDataUrl.KUAIDICHAXUN_PARAM2 + number + NetWorkDataUrl.KUAIDICHAXUN_PARAM3 + time + NetWorkDataUrl.KUAIDICHAXUN_PARAM4;
        try {
            HttpUtils.doPostAsyn(NetWorkDataUrl.KUAIDICHAXUN_URL, param, new HttpUtils.CallBack() {
                @Override
                public void onRequestComplete(String result) {
                    Gson gson = new Gson();
                    kuaiDiJieGuoDataEntity = gson.fromJson(result, KuaiDiJieGuoDataEntity.class);
                    if (kuaiDiJieGuoDataEntity.getShowapi_res_body().getData().size() > 0) {
                        //if (kuaiDiJieGuoDataEntity.getShowapi_res_body().isFlag()) {
                        handler.sendEmptyMessage(2);
                        //} else {
                        //  tv_error.setVisibility(View.VISIBLE);
                        // }
                    } else {
                        handler.sendEmptyMessage(0);
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    //recyclerview_kuaidi.setVisibility(View.INVISIBLE);

                    Snackbar.make(relativeLayout_kuaidi, "没有数据，请核实快递公司或者快递单号！", Snackbar.LENGTH_SHORT).show();
                    break;
                case 1:
                    recyclerview_kuaidi.setVisibility(View.VISIBLE);
                    namelists = new ArrayList<>();
                    company = new ArrayMap<String, String>();
                    for (int i = 0; i < kuaiDiGongSiDataEntity.getShowapi_res_body().getExpressList().size(); i++) {
                        namelists.add(kuaiDiGongSiDataEntity.getShowapi_res_body().getExpressList().get(i).getExpName());
                        company.put(kuaiDiGongSiDataEntity.getShowapi_res_body().getExpressList().get(i).getExpName(), kuaiDiGongSiDataEntity.getShowapi_res_body().getExpressList().get(i).getSimpleName());
                    }
                    ArrayAdapter<String> arrayadapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_dropdown_item, namelists);
                    appcompatspinner_kuaidi.setAdapter(arrayadapter);
                    appcompatspinner_kuaidi.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                        @Override
                        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                            simpleName = company.get(namelists.get(position));
                        }

                        @Override
                        public void onNothingSelected(AdapterView<?> parent) {

                        }
                    });
                    break;
                case 2:
                    kuaiDiAdapter = new KuaiDiAdapter(getActivity(), kuaiDiJieGuoDataEntity);
                    recyclerview_kuaidi.setAdapter(kuaiDiAdapter);
                    break;
            }
        }
    };

    private class TextChange implements TextWatcher {

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            number = et_kuaidi.getText().toString();
            if (number.length() > 0) {
                btn_find_kuaidi.setEnabled(true);
            } else {
                btn_find_kuaidi.setEnabled(false);
            }
            if (number.length() > 0) {
                btn_reset_kuaidi.setEnabled(true);
            } else {
                btn_reset_kuaidi.setEnabled(false);
            }
        }

        @Override
        public void afterTextChanged(Editable s) {
            number = et_kuaidi.getText().toString();
        }
    }

}
